import { getUserDetailByIdApi, getUserInfoApi, loginApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, form) {
      // 1. 发请求
      const res = await loginApi(form)
      // 2. 存token
      context.commit('setToken', res.data)
      // 3. 返回res, 供vue文件使用 去做提示处理
      return res
    },
    async getUserInfo(context) {
      const res = await getUserInfoApi()
      const { data: data2 } = await getUserDetailByIdApi(res.data.userId)
      // console.log(data2)
      // console.log(res)
      const result = { ...res.data, ...data2 }
      context.commit('setUserInfo', result)
      return res.data
    },
    // 没有异步，但一次调用两个方法
    logout({ commit }) {
      commit('removeUserInfo')
      commit('removeToken')
    }
  }
}
